package com.javabasic.algorithm.sangfor_interview;

import org.junit.Test;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author mir.xiong
 * @version 1.0
 * @description
 * 有两个数组
 * - [1,2,3,32,4,5,32,6,5]
 * - [32,3,42,5]
 * 两个数组中均有的元素有：32、3、5
 * 去除两个数组中的共有元素合成一个数组：[1,2,4,6,42](顺序可以不用保持原来的顺序)
 * @see
 * @since Created by work on 2021/12/26 10:41 下午
 */
public class DeleteCommonElements {

    @Test
    public void deleteCommonElementsTest() {
        int[] arr1 = new int[]{1,2,3,32,4,5,32,6,5};
        int[] arr2 = new int[]{32,3,42,5};
        int[] result = deleteCommonElements(arr1, arr2);
        int len = result.length;
        for (int i = 0; i < len; i++) {
            System.out.print(result[i] + " ");
        }
    }

    public int[] deleteCommonElements(int[] arr1, int[] arr2) {
        Map<Integer, Integer> keyToNums1 = new HashMap<>(16);
        Map<Integer, Integer> keyToNums2 = new HashMap<>(16);
        int num;
        for (int element : arr1) {
            num = keyToNums1.getOrDefault(element, 0);
            num++;
            keyToNums1.put(element, num);
        }
        for (int element : arr2) {
            num = keyToNums2.getOrDefault(element, 0);
            num++;
            keyToNums2.put(element, num);
        }
        List<Integer> resultList = new ArrayList<>();
        for (Map.Entry<Integer, Integer> entry : keyToNums1.entrySet()) {
            if (keyToNums2.containsKey(entry.getKey())) {
                keyToNums2.remove(entry.getKey());
                continue;
            }
            num = entry.getValue();
            for (int i = 0; i < num; i++) {
                resultList.add(entry.getKey());
            }
        }
        for (Map.Entry<Integer, Integer> entry : keyToNums2.entrySet()) {
            num = entry.getValue();
            for (int i = 0; i < num; i++) {
                resultList.add(entry.getKey());
            }
        }
        int[] result = new int[resultList.size()];
        num = 0;
        for (Integer integer : resultList) {
            result[num++] = integer;
        }
        return result;
    }
}
